package com.hoperun.product.activity

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.KeyEvent
import android.view.View
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.JsonUtils
import com.blankj.utilcode.util.StringUtils
import com.blankj.utilcode.util.ToastUtils
import com.honeywell.aidc.BarcodeFailureEvent
import com.honeywell.aidc.BarcodeReadEvent
import com.honeywell.aidc.BarcodeReader
import com.hoperun.distributecloth.R
import com.hoperun.product.base.BaseActivity
import com.hoperun.product.base.BaseEntity
import com.hoperun.product.entity.ClothEntity
import com.hoperun.product.net.IServiceImpl
import com.hoperun.product.net.RequestServiceImpl
import com.hoperun.product.net.WebServiceAccessUtils
import com.hoperun.product.view.SimpleDialog
import kotlinx.android.synthetic.main.activity_in_bound_layout.*
import kotlinx.android.synthetic.main.main_activity.*
import org.jetbrains.anko.sdk27.coroutines.onClick
import org.json.JSONArray


/**
 * 入库
 */
class InBoundActivity : BaseActivity(), BarcodeReader.BarcodeListener {


    var isJudgeSuccess = false


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_in_bound_layout)
        initView()
    }

    fun initView() {
        backBtn.onClick { finish() }
        confirmBtn.onClick { }
        whlocNoEt.setOnKeyListener(View.OnKeyListener { v, keyCode, event ->
            if (event != null && event.keyCode == KeyEvent.KEYCODE_ENTER && event.action == KeyEvent.ACTION_UP) {
                startStorehouseJudge()
                return@OnKeyListener true
            }
            false
        })
        whlocNoEt.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {
                isJudgeSuccess = false
                //库位需要重新校验
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

            }

        })

        confirmBtn.onClick { startInBound() }
    }


    /**
     * 入库校验
     */
    fun startStorehouseJudge() {
        val whlocNo = whlocNoEt.text.toString().trim()
        if (whlocNo.isEmpty()) {
            ToastUtils.showLong("请输入库位")
            return
        }
        showWait()
        RequestServiceImpl.storehouseJudge(mMIPHandler, IServiceImpl.storehouseJudge, whlocNo)
    }

    /**
     * 入库
     */
    fun startInBound() {
        if (!isJudgeSuccess) {
            ToastUtils.showLong("请先校验库位！")
            return
        }
        val txm = txmEt.text.toString().trim()
        val whlocNo = whlocNoEt.text.toString().trim()
        if (txm.isEmpty()) {
            ToastUtils.showLong("请输入条码！")
            return
        }
        if (whlocNo.isEmpty()) {
            ToastUtils.showLong("请输入库位！")
            return
        }
        showWait()
        RequestServiceImpl.inboundConfirm(mMIPHandler, IServiceImpl.inboundConfirm, whlocNo, txm)

    }

    /**
     * 霍尼韦尔扫码监听
     */
    override fun onBarcodeEvent(event: BarcodeReadEvent?) {
        runOnUiThread {
            //            val codeDate = event?.getBarcodeData()
//            if (!TextUtils.isEmpty(codeDate)) {
//
//                if (whlocNoEt.hasFocus()) {
//                    whlocNoEt.setText(codeDate)
//                    startStorehouseJudge()
//                }
//            }
        }
    }

    override fun onFailureEvent(event: BarcodeFailureEvent?) {
        runOnUiThread {
            toast("onTriggerEvent")
        }

    }

    override fun onPostHandle(requestType: Int, objBody: Any?, error: Boolean) {

        if (error) {
            when (requestType) {
                IServiceImpl.storehouseJudge -> {
                    val result = GsonUtils.fromJson(objBody.toString(), BaseEntity::class.java)
                    if (result.OPT_FLAG == "SUCCESS") {
                        isJudgeSuccess = true
                        ToastUtils.showLong(result.MSG_INFO)
                    } else {
                        ToastUtils.showLong(result.MSG_INFO)
                    }
                }
                IServiceImpl.inboundConfirm -> {
                    val result = GsonUtils.fromJson(objBody.toString(), BaseEntity::class.java)
                    if (result.OPT_FLAG == "SUCCESS") {
                        //入库成功后清空面数据
                        whlocNoEt.setText("")
                        txmEt.setText("")
                        txmEt.requestFocus()
                        SimpleDialog.show(this, result.MSG_INFO)
                    } else {
                        SimpleDialog.show(this, result.MSG_INFO)
                    }
                }
            }
        } else {
            ToastUtils.showLong(objBody.toString())
        }
        stopWait()
    }

    /************************************霍尼韦尔***************************************/
    private val ACTION_BARCODE_DATA = "com.honeywell.sample.action.BARCODE_DATA"
    private val ACTION_CLAIM_SCANNER = "com.honeywell.aidc.action.ACTION_CLAIM_SCANNER"
    private val ACTION_RELEASE_SCANNER = "com.honeywell.aidc.action.ACTION_RELEASE_SCANNER"
    private val EXTRA_SCANNER = "com.honeywell.aidc.extra.EXTRA_SCANNER"
    private val EXTRA_PROFILE = "com.honeywell.aidc.extra.EXTRA_PROFILE"
    private val EXTRA_PROPERTIES = "com.honeywell.aidc.extra.EXTRA_PROPERTIES"
    private val barcodeDataReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            if (ACTION_BARCODE_DATA == intent.action) {
                val version = intent.getIntExtra("version", 0)
                if (version >= 1) {
                    val data = intent.getStringExtra("data")
                    //ToastUtils.showLong("接收到霍尼韦尔广播数据")
                    if (txmEt.hasFocus()) {
                        txmEt.setText(data)
                        whlocNoEt.requestFocus()
                    } else {
                        whlocNoEt.setText(data)
                        startStorehouseJudge()
                    }
                }


            }
        }
    }
    private fun claimScanner() {
        val properties = Bundle()

        properties.putBoolean("DPR_DATA_INTENT", true)
        properties.putString("DPR_DATA_INTENT_ACTION", ACTION_BARCODE_DATA)

        sendBroadcast(
            Intent(ACTION_CLAIM_SCANNER).putExtra(
                EXTRA_SCANNER,
                "dcs.scanner.imager"
            ).putExtra(EXTRA_PROFILE, "MyProfile1").putExtra(EXTRA_PROPERTIES, properties)
        )
    }

    private fun releaseScanner() {
        sendBroadcast(Intent(ACTION_RELEASE_SCANNER))
    }
    override fun onResume() {
        super.onResume()
        registerReceiver(barcodeDataReceiver, IntentFilter(ACTION_BARCODE_DATA))
        claimScanner()
    }

    override fun onPause() {
        super.onPause()
        unregisterReceiver(barcodeDataReceiver)
        releaseScanner()
    }
    /************************************霍尼韦尔***************************************/

}